package com.supor.aiot.mine.ui.wish;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.android.baseconfig.common.entity.IntervalItemDecoration;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.RefreshHelper;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.bean.Dictionary;
import com.supor.aiot.mine.bean.SelectDevice;
import com.supor.aiot.mine.bean.WishBean;
import com.supor.aiot.mine.databinding.ActivityAddWishBinding;
import com.supor.aiot.mine.ui.adapter.DeviceAdapter;
import com.supor.aiot.mine.ui.adapter.DictionaryAdapter;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: WishActivity <br>
 * 作者: lei <br>
 * 日期: 2021/8/31 <br>
 */
public class AddWishActivity extends BaseMVVMActivity<AddWishViewModel, ActivityAddWishBinding> implements View.OnClickListener {

    private BaseQuickAdapter deviceAdapter;
    private BaseQuickAdapter tasteAdapter;
    List<Dictionary> dictionaryList;

    @Override
    protected int resourceId() {
        return R.layout.activity_add_wish;
    }

    @Override
    protected void initView() {
        super.initView();
        Intent intent = getIntent();
        dictionaryList = intent.getParcelableArrayListExtra(Constants.Key.TASTE_LIST);
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        bindingView.btnSave.setEnabled(false);

        bindingView.btnSave.setOnClickListener(this);
        bindingView.tvCheckState.setOnClickListener(this);
        bindingView.tvSlideTip.setOnClickListener(v ->
                bindingView.slideBtn.setOpen(!bindingView.slideBtn.isOpen()));
        bindingView.llConfirmAction.setOnClickListener(v ->
                bindingView.slideBtn.setOpen(!bindingView.slideBtn.isOpen()));
        bindingView.slideBtn.setOnSlideButtonChangeListener((view, isOpen) -> {
            bindingView.tvSlideTip.setSelected(isOpen);
            bindingView.llConfirmAction.setSelected(isOpen);
        });
        initRecyclerView();
    }

    private void initRecyclerView() {

        // BindDevice布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        bindingView.rcvDevice.setLayoutManager(linearLayoutManager);
        bindingView.rcvDevice.setOverScrollMode(View.OVER_SCROLL_NEVER);
        bindingView.rcvDevice.setNestedScrollingEnabled(false);
        bindingView.rcvDevice.addItemDecoration(
                new IntervalItemDecoration(getResources().getDimensionPixelSize(R.dimen.dp_5),
                        getResources().getDimensionPixelSize(R.dimen.dp_1),
                        getResources().getDimensionPixelSize(R.dimen.dp_5),
                        getResources().getDimensionPixelSize(R.dimen.dp_1), false));

        List<SelectDevice> deviceList = new ArrayList<>();
        if (GlobalDataCache.deviceTree != null) {
            for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                SelectDevice device = new SelectDevice();
                device.deviceInfo = info;
                deviceList.add(device);
            }
        }
        deviceAdapter = new DeviceAdapter(deviceList);
        bindingView.rcvDevice.setOnItemClickListener((v, position) -> {
            Logc.e("onItemClick: position: " + position);
            List<SelectDevice> list = deviceAdapter.getData();
            for (SelectDevice device : list) {
                device.isSelect = false;
            }
            SelectDevice selectDevice = list.get(position);
            selectDevice.isSelect = true;
            deviceAdapter.notifyDataSetChanged();
            if (!bindingView.btnSave.isEnabled()) {
                bindingView.btnSave.setEnabled(true);
            }
        });
        bindingView.rcvDevice.setAdapter(deviceAdapter);

        // taste
        RefreshHelper.initGrid(bindingView.rcvTaste, 5,
                getResources().getDimensionPixelSize(R.dimen.dp_5));

        tasteAdapter = new DictionaryAdapter(dictionaryList);
        bindingView.rcvTaste.setOnItemClickListener((v, position) -> {
            Logc.e("onItemClick: position: " + position);
            List<Dictionary> list = tasteAdapter.getData();
            Dictionary dictionary = list.get(position);
            dictionary.isSelect = !dictionary.isSelect;
            tasteAdapter.notifyItemChanged(position);
        });
        bindingView.rcvTaste.setAdapter(tasteAdapter);
    }

    @Override
    protected void initData() {
        super.initData();

        viewModel.getOperationResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Success) {
                setResult(1);
                finish();
            } else if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("增加心愿失败");
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_save) {
            String name = bindingView.etWishName.getInputText();
            if (TextUtils.isEmpty(name)) {
                ToastUtils.getInstance().showCustomToast("心愿名称不能为空");
                return;
            }
            String des = bindingView.etWishDes.getInputText();
            if (TextUtils.isEmpty(des)) {
                ToastUtils.getInstance().showCustomToast("心愿描述不能为空");
                return;
            }
            List<SelectDevice> list = deviceAdapter.getData();
            SelectDevice selectDevice = null;
            for (SelectDevice device : list) {
                if (device.isSelect) {
                    selectDevice = device;
                    break;
                }
            }
            if (selectDevice == null) {
                ToastUtils.getInstance().showCustomToast("必须选择设备");
                return;
            }
            List<Dictionary> dictionaryList = tasteAdapter.getData();
            StringBuilder sb = new StringBuilder();
            for (Dictionary dictionary : dictionaryList) {
                if (dictionary.isSelect) {
                    sb.append(dictionary.dictionaryBean.getSysCodeSub());
                    sb.append(",");
                }
            }
            sb.delete(sb.length() - 1, sb.length());

            WishBean wishBean = new WishBean();
            wishBean.wishName = name;
            wishBean.wishDescription = des;
            wishBean.modelName = selectDevice.deviceInfo.devAlias;
            wishBean.modelId = selectDevice.deviceInfo.pid;
            wishBean.tastes = sb.toString();
            wishBean.isNotified = bindingView.slideBtn.isOpen() ? 1 : 0;

            showLoading();
            viewModel.addWish(wishBean);

        } else if (v.getId() == R.id.tv_check_state){
            if (bindingView.clWishTip.getVisibility() == View.GONE) {
                bindingView.clWishTip.setVisibility(View.VISIBLE);
                bindingView.tvCheckState.setText(R.string.pack_up_state);
                bindingView.tvCheckState.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_wish_up, null),
                        null);
            } else {
                bindingView.clWishTip.setVisibility(View.GONE);
                bindingView.tvCheckState.setText(R.string.check_state);
                bindingView.tvCheckState.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_wish_down, null),
                        null);
            }
        }
    }
}
